<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="songForm">

    <el-row>
      <el-col :span="8">
        <el-form-item label="歌曲名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="8">
        <el-form-item label="歌手" prop="singer">
          <el-input v-model="ruleForm.singer"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item>
      <el-button type="primary" @click="handleSubmit">修 改/新 增</el-button>
      <el-button @click="goBack">返 回</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import api from "@/api/api";

const SUCCESS = 0;
export default {
  data() {
    return {
      ruleForm: {
        id: null,
        name: "",
        singer: ""
      },
      rules: {
        name: [
          { required: true, message: "请填写歌曲名称", trigger: "change" }
        ],
        singer: [{ required: true, message: "请填写歌手", trigger: "change" }]
      }
    };
  },
  created() {
    let id = this.$route.query.id;
    if (id) {
      this.ruleForm.id = id;
      this._getDetail();
    }
  },
  methods: {
    _getDetail() {
      api.getDetail(this.ruleForm.id).then(response => {
        if (response.code == SUCCESS) {
          this.ruleForm = response.data;
        }
      });
    },
    handleSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          console.log("submit!");
          this._addOrUpdate();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    _addOrUpdate() {
      api.addOrUpdate(this.ruleForm).then(data => {
        if (data.code == SUCCESS) {
          this.$message({
            type: "success",
            message: "操作成功"
          });
          this.$router.push({ path: "/list" });
        } else {
          this.$message({
            type: "info",
            message: "操作失败"
          });
        }
      });
    },
    goBack() {
      this.$router.back();
    }
  }
};
</script>

<style lang="less">
.songForm {
  padding: 20px;
}
</style>